<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item :label="$t('terminal.insertTitle')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('terminal.insertTitleInput')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('program.status')" prop="status">
        <el-select v-model="queryParams.status" :placeholder="$t('equipment.statusSelect')" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('elButton.establishTime')">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          :start-placeholder="$t('elButton.startTime')"
          :end-placeholder="$t('elButton.endTime')"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('elButton.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('elButton.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['caption_add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{ $t('elButton.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['caption_edit']"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit"
        >{{ $t('elButton.change') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['caption_del']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDel"
        >{{ $t('elButton.delete') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['caption_export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >{{ $t('elButton.export') }}
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" :content="$t('elButton.refresh')" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? $t('elButton.hideSearch') : $t('elButton.showSearch')" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="captionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('equipment.number')" width="55" align="center" prop="id" />
      <el-table-column :label="$t('terminal.insertTitle')" align="center" prop="name" />
      <el-table-column :label="$t('terminal.insertAddress')" align="center" prop="position">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.position == 'top'" type="info">{{ $t('terminal.insertAddress1') }}</el-tag>
          <el-tag v-if="scope.row.position == 'bottom'" type="success">{{ $t('terminal.insertAddress2') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('terminal.speed')" align="center" prop="speed" />
      <el-table-column :label="$t('terminal.direction')" align="center" prop="direction">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.direction == 'up'" type="info">{{ $t('terminal.top') }}</el-tag>
          <el-tag v-if="scope.row.direction == 'down'" type="success">{{ $t('terminal.bottom') }}</el-tag>
          <el-tag v-if="scope.row.direction == 'left'" type="info">{{ $t('terminal.left') }}</el-tag>
          <el-tag v-if="scope.row.direction == 'right'" type="success">{{ $t('terminal.right') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('terminal.fontSize')" align="center" prop="fontSize" />
      <el-table-column :label="$t('terminal.insertContent')" align="center" prop="content" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('terminal.insertWay')" align="center" prop="mode">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.mode == '0'" type="info">{{ $t('terminal.insertWay1') }}</el-tag>
          <el-tag v-if="scope.row.mode == '1'" type="success">{{ $t('terminal.insertWay2') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('program.status')" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column :label="$t('equipment.remarks')" align="center" prop="remarks" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('elButton.establishTime')" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.control')" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == '0'"
            v-hasPerm="['caption_audit']"
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleAudit(scope.row)"
          >{{ $t('elButton.examine') }}
          </el-button>
          <el-button
            v-hasPerm="['caption_edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >{{ $t('elButton.change') }}
          </el-button>
          <el-button
            v-hasPerm="['caption_del']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDel(scope.row)"
          >{{ $t('elButton.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改插播对话框 -->
    <el-dialog :title="title" :visible.sync="open" :fullscreen="true" :modal-append-to-body="true" :append-to-body="true">
      <el-row>
        <el-col :span="12">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="20">
                <el-form-item :label="$t('terminal.insertTitle')" prop="name">
                  <el-input v-model="form.name" :placeholder="$t('terminal.insertTitleInput')" size="small" />
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item :label="$t('terminal.insertContent')" prop="content">
                  <el-input
                    v-model="form.content"
                    type="textarea"
                    rows="4"
                    maxlength="500"
                    show-word-limit
                    :placeholder="$t('terminal.insertContentInput')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('terminal.insertAddress')" prop="position">
                  <el-select v-model="form.position" :placeholder="$t('terminal.insertAddressInput')">
                    <el-option :label="$t('terminal.insertAddress1')" value="top" />
                    <el-option :label="$t('terminal.insertAddress2')" value="bottom" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('terminal.rollingDirection')" prop="direction">
                  <el-select v-model="form.direction" :placeholder="$t('terminal.rollingDirectionSelect')">
                    <el-option :label="$t('terminal.toTop')" value="up" />
                    <el-option :label="$t('terminal.toLeft')" value="down" />
                    <el-option :label="$t('terminal.toRight')" value="left" />
                    <el-option :label="$t('terminal.toBottom')" value="right" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('program.rollingSpeed')" prop="speed">
                  <el-select v-model="form.speed" :placeholder="$t('program.rollingSpeedInput')">
                    <el-option :label="$t('program.rollingSpeed1')" value="5000" />
                    <el-option :label="$t('program.rollingSpeed2')" value="3000" />
                    <el-option :label="$t('program.rollingSpeed3')" value="2000" />
                    <el-option :label="$t('program.rollingSpeed4')" value="1000" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('terminal.fontSize')" prop="fontSize">
                  <el-select v-model="form.fontSize" :placeholder="$t('program.fontSizeInput')">
                    <el-option label="16" value="16" />
                    <el-option label="20" value="20" />
                    <el-option label="24" value="24" />
                    <el-option label="28" value="28" />
                    <el-option label="32" value="32" />
                    <el-option label="36" value="36" />
                    <el-option label="40" value="40" />
                    <el-option label="60" value="60" />
                    <el-option label="80" value="80" />
                    <el-option label="100" value="100" />
                    <el-option label="150" value="150" />
                    <el-option label="200" value="200" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('terminal.fontColor')" prop="fontColor">
                  <el-color-picker v-model="form.fontColor" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('terminal.backgroundColor')" prop="bgColor">
                  <el-color-picker v-model="form.bgColor" show-alpha />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item :label="$t('terminal.insertWay')" prop="mode">
                  <el-radio-group v-model="form.mode">
                    <el-radio key="0" label="0">{{ $t('terminal.insertWay1') }}</el-radio>
                    <el-radio key="1" label="1">{{ $t('terminal.insertWay2') }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col v-if="form.mode == 0" :span="14">
                <el-form-item :label="$t('terminal.startTime')" prop="startTime">
                  <el-date-picker
                    v-model="form.startTime"
                    clearable
                    size="small"
                    style="width: 200px"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :placeholder="$t('terminal.chooseStartTime')"
                  />
                  <el-date-picker
                    v-model="form.stopTime"
                    clearable
                    size="small"
                    style="width: 200px"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :placeholder="$t('terminal.chooseEndTime')"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="form.mode == 1" :span="14">
                <el-form-item :label="$t('program.playTime')" prop="duration">
                  <el-input-number v-model="form.duration" :placeholder="$t('program.playTimeInput')" />
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item :label="$t('equipment.remarks')" prop="remarks">
                  <el-input
                    v-model="form.remarks"
                    type="textarea"
                    rows="3"
                    maxlength="200"
                    show-word-limit
                    :placeholder="$t('equipment.remarksInput')"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="12">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ $t('equipment.list') }}</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="openDevice">{{ $t('equipment.add') }}</el-button>
            </div>
            <div class="device-wrapper">
              <el-table
                ref="devices"
                :data="devices"
                style="width: 100%"
              >
                <el-table-column
                  :label="$t('equipment.name')"
                  prop="name"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                />
                <el-table-column
                  :label="$t('equipment.resolving')"
                  prop="resolution"
                  header-align="center"
                  align="center"
                  :show-overflow-tooltip="true"
                />
                <el-table-column prop="online" :label="$t('program.status')" header-align="center" align="center">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.online == '0'" type="danger">{{ $t('equipment.isUnderline') }}</el-tag>
                    <el-tag v-if="scope.row.online == '1'" type="success">{{ $t('equipment.isOnline') }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('equipment.control')" width="180px" header-align="center" align="center">
                  <template slot-scope="scope">
                    <div class="operation">
                      <el-button size="mini" @click="handleDeviceDelete(scope.$index)">{{ $t('elButton.delete') }}</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('submit') }}</el-button>
        <el-button @click="cancel">{{ $t('cancelText') }}</el-button>
      </div>
    </el-dialog>

    <!-- 添加设备对话框 -->
    <el-dialog :title="$t('equipment.add')" :visible.sync="deviceOpen" :modal-append-to-body="true" :append-to-body="true">
      <div class="table-wrapper">
        <div class="group">
          <div class="head-container">
            <el-input
              v-model="name"
              :placeholder="$t('equipment.channelNameInput')"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              ref="tree"
              :data="groupOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              default-expand-all
              @node-click="handleNodeClick"
            >
              <div slot-scope="{ node, data }" class="el-tree-node__label custom-tree-node custom-tree-item">
                {{ data.name }}
              </div>
            </el-tree>
          </div>
        </div>
        <div class="right-wrap">
          <div class="search">
            <el-form ref="form" :model="params">
              <el-row>
                <el-col :span="6">
                  <el-form-item prop="name">
                    <el-input v-model="params.name" size="small" :placeholder="$t('equipment.nameInput')" />
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="btns-col">
                  <el-button size="small" type="primary" @click="handleSearch">{{ $t('elButton.search') }}</el-button>
                  <el-button size="small" @click="handleClear">{{ $t('elButton.clear') }}</el-button>
                  <el-tooltip class="item" effect="dark" :content="$t('elButton.refresh')" placement="top">
                    <el-button size="small" circle icon="el-icon-refresh" @click="refresh()" />
                  </el-tooltip>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <el-table
            ref="deviceTable"
            :data="deviceList"
            :border="true"
          >
            <el-table-column header-align="center" align="center" type="selection" />
            <el-table-column
              prop="name"
              :label="$t('equipment.name')"
              header-align="center"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              prop="groupName"
              :label="$t('equipment.sortTitle')"
              header-align="center"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              prop="resolution"
              :label="$t('equipment.resolving')"
              header-align="center"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column prop="online" :label="$t('program.status')" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.online == '0'" type="danger">{{ $t('equipment.isUnderline') }}</el-tag>
                <el-tag v-if="scope.row.online == '1'" type="success">{{ $t('equipment.isOnline') }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="selectDevice">{{ $t('submitText') }}</el-button>
        <el-button @click="deviceCancel">{{ $('cancelText') }}</el-button>
      </div>
    </el-dialog>

    <!--审核页面-->
    <audit
      :obj="auditObj"
      :visible.sync="auditVisible"
      :audit-title="$('program.issuingShenhe')"
      audit-type="caption"
      @refresh="getList"
    >
      <h3>{{ $('program.channelShenheTitle') }}</h3>
    </audit>
  </div>
</template>

<script>
import { listCaption, getCaption, delCaption, addCaption, editCaption, exportCaption } from '@/api/ips/caption'
import { listDevice } from '@/api/ips/device'
import { groupTree } from '@/api/ips/group'
import AuditMixin from '@/mixins/audit/index.js'

export default {
  name: 'Caption',
  mixins: [AuditMixin],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 插播表格数据
      captionList: [],
      devices: [],
      deviceList: [],
      // 过滤分组用
      name: '',
      groupOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      deviceOpen: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 日期范围
      dateRange: [],
      // 状态字典
      statusOptions: [], // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        status: undefined,
        createTime: undefined
      },
      params: {
        name: '',
        playMode: '1'
      },
      // 显示搜索条件
      showSearch: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: this.$t('terminal.insertTitleEmpty'), trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('terminal.insertContentEmpty'), trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {
    // 根据名称筛选分组名称树
    name(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getDicts('check_status').then(response => {
      this.statusOptions = response.data
      this.statusOptions.push({
        label: this.$t('expired'),
        value: '1'
      })
    })
  },
  methods: {
    /** 查询分组名称下拉树结构 */
    getGroupTree() {
      groupTree().then(response => {
        this.groupOptions = response.data
      })
    },
    /** 查询设备列表 */
    getDeviceList() {
      listDevice(this.params)
        .then((res) => {
          this.deviceList = res.data
        })
        .catch(() => {
        })
    },
    /** 点击搜索按钮触发 */
    handleSearch() {
      this.getDeviceList()
    },
    /** 点击清空按钮触发 */
    handleClear() {
      this.params = {
        name: '',
        playMode: '1'
      }
      this.getDeviceList()
    },
    // 取消按钮
    deviceCancel() {
      this.deviceOpen = false
    },
    /** 点击刷新按钮触发 */
    refresh() {
      this.getDeviceList()
    },
    selectDevice() {
      const sdata = this.$refs.deviceTable.selection.map(item => {
        return {
          id: item.id,
          name: item.name,
          code: item.code,
          resolution: item.resolution,
          platFlag: item.platFlag,
          online: item.online
        }
      })
      for (const index in sdata) {
        this.$set(this.devices, index, sdata[index])
      }
      this.deviceOpen = false
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.params.groupId = (data.id === 0 ? null : data.id)
      this.getList()
    },
    handleDeviceDelete(index) {
      this.devices.splice(index, 1)
    },
    /** 查询插播列表 */
    getList() {
      this.loading = true
      listCaption(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.captionList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        position: 'bottom',
        speed: '3000',
        direction: 'left',
        fontSize: '24',
        fontColor: '#ED4014',
        bgColor: '#FFFFFF',
        content: undefined,
        devices: undefined,
        mode: '1',
        startTime: undefined,
        stopTime: undefined,
        duration: 60,
        deptId: undefined,
        status: '0'
      }
      this.devices = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    openDevice() {
      this.deviceOpen = true
      this.getGroupTree()
      this.getDeviceList()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = this.$t('program.insertMessageAdd')
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.reset()
      const id = row.id || this.ids
      getCaption(id).then(response => {
        this.form = response.data
        this.devices = JSON.parse(this.form.devices)
        this.open = true
        this.title = this.$t('program.insertMessageChange')
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // if (!this.devices || (this.devices && this.devices.length === 0)) {
          //   this.msgError('请选择设备')
          //   return
          // }
          this.form.devices = JSON.stringify(this.devices)
          if (this.form.id !== undefined) {
            editCaption(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('loginLog.changeSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addCaption(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('addSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDel(row) {
      const ids = row.id || this.ids
      this.$confirm(this.$t('program.insertMessageDelete') + ids + this.$t('equipment.deleteEquipment2'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return delCaption(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('deleteSuccess'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm(this.$t('program.exportAllinsertMessage'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return exportCaption(queryParams)
      }).then(response => {
        this.download(response.data)
      }).catch(function() {
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  /deep/ .dialog-footer {
    text-align: center;
    width: 100%;

    &:after {
      content: "";
      display: block;
      clear: both;
    }
  }

  .table-wrapper {
    &:after {
      content: '';
      display: block;
      clear: both;
    }

    > .group {
      float: left;
      width: 200px;
    }

    > .right-wrap {
      float: left;
      width: calc(100% - 208px);
      margin-left: 8px;
    }
  }

  .btns-col {
    .el-button {
      margin-left: 8px;
      margin-top: 2px;
    }
  }
</style>
